package org.atovio.coolexam.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.atovio.coolexam.annotation.AuthAccess;
import org.atovio.coolexam.common.Result;
import org.atovio.coolexam.exception.RequestException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@RestController
@RequestMapping("/files")
public class FileController {

    // 本项目存储文件的目录路径
    private static final String FILES_PATH = System.getProperty("user.dir") + File.separator + "file-space";

    @PostMapping
    public Result upload(MultipartFile file, HttpServletRequest request) throws IOException {
        String originalFilename = file.getOriginalFilename(); // 获取文件原始名称
        if (StrUtil.isBlank(originalFilename))
            throw new RequestException("请求错误，缺少文件源");
        String extName = FileUtil.extName(originalFilename); // 获取文件名后缀

        // ================  创建项目文件存储目录 ===================
        // 本项目存储文件的真实目录
        // 检测文件存储目录是否存在。如果目录不存在，创建它
        if (!FileUtil.exist(FILES_PATH))
            FileUtil.mkdir(FILES_PATH);

        // ================  创建需要存储的文件,并将其写入硬盘 ===================
        // 对文件的处理是，防止文件原名不规范（即有空格或其他字符），一律重命名
        String filePath = FILES_PATH + File.separator;
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuuMMddHHmmssSSS");
        String currentTime = formatter.format(LocalDateTime.now());
        originalFilename = currentTime + "." + extName;
        File savingFile = new File(filePath + originalFilename); // 要存的文件
        // 将文件写入硬盘
        file.transferTo(savingFile);

        // ======================  返回该文件的URI =======================
        // 准备提供已存储文件的uri
        // 获取项目域名url
        String projectUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
        String fileUri = projectUrl + "/files/" + originalFilename;
        return Result.success(fileUri); // 返回文件的链接
    }

    @AuthAccess
    @GetMapping("/{fileName}")
    public void download(HttpServletResponse response, @PathVariable String fileName) throws IOException {
        String filePath = FILES_PATH + File.separator + fileName;
        if (!FileUtil.exist(filePath))
            return;
        // 获取文件字节数组
        byte[] bytes = FileUtil.readBytes(filePath);
        ServletOutputStream os = response.getOutputStream();
        os.write(bytes);
        os.flush();
        os.close();
    }
}
